//
//  MPMarkView.m
//  MarkPlatform
//
//  Created by xiao6 on 2018/1/8.
//  Copyright © 2018年 AT. All rights reserved.
//

#import "MPMarkView.h"
#import "ATCropView.h"

@interface MPMarkViewPoint : UIView
@end
@implementation MPMarkViewPoint
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}
- (void)setup {
    self.backgroundColor = [[UIColor appColor] colorWithAlphaComponent:0.7f];
    self.clipsToBounds = YES;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.cornerRadius = self.height/2;
}
@end

@interface MPMarkViewRect : UIView
@property (nonatomic, assign) CGRect rect;
@end
@implementation MPMarkViewRect
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}
- (void)setup {
    self.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.5f];
}
- (void)drawRect:(CGRect)rect {
    
}
@end
@interface MPMarkView ()
@property (nonatomic, weak) ATCropView *rectView;
@end
@implementation MPMarkView
- (void)setStep:(MPMarkStep *)step {
    _step = step;
    
    self.rectView = nil;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (MPMarkModel *model in step.markModels) {
        if (model.way == MPMarkTypePoint) {
            MPMarkViewPoint *pointView = [[MPMarkViewPoint alloc] initWithFrame:CGRectMake(0, 0, 12, 12)];
            pointView.center = model.viewRect.origin;
            [self addSubview:pointView];
        }
        else if (model.way == MPMarkTypeRect) {
            ATCropView *rectView = [[ATCropView alloc] initWithSuperview:self frame:self.bounds];
            rectView.clippingRect = model.viewRect;
            rectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            @weakify(self)
            rectView.clippingRectDidChange = ^(ATCropView *cropView) {
                @strongify(self)
                !self.rectDidChange ?: self.rectDidChange(self, cropView.clippingRect);
            };
            self.rectView = rectView;
        }
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (self.rectView && CGPointGetDistanceToPoint(point, CGRectGetCenter(self.rectView.clippingRect)) < 15) {
        return self.rectView;
    }
    return view;
}
@end
